#include "datamanager.h"
#include <QSqlQuery>
#include <QSqlError>
#include <QJsonDocument>
#include <QJsonObject>
#include <QDebug>
#include <QFile>
#include <QTimer>
#include "config.h"
#include <iostream>
#include <memory.h>
#include <spdlog/spdlog.h>
#include "log/log.h"
#include "common/configmanager/configmanager.h"
std::unique_ptr <CDataManager> CDataManager::m_InStance = nullptr;
std::once_flag CDataManager::m_Flag;

CDataManager& CDataManager::GetInstance()
{
    std::call_once(m_Flag,[](){
        m_InStance.reset(new CDataManager());
    });
    return *m_InStance;
}

CDataManager::CDataManager():m_dbPath(""), m_position("") {
    // 从配置文件或环境变量中读取数据库路
    std::shared_ptr<CConfigManager> pCfgManager = CConfigManager::GetInstance();
    if(pCfgManager !=nullptr){
        std::string stdPath ="E:\\wlr\\cfg\\json.cfg";
       Json::Value tmpValue = Json::Value::null;
        if(!pCfgManager->loadConfig(stdPath, tmpValue)){
            qDebug()<<"load Config failed";
            return;
        }
        if(tmpValue.isMember("DataBase") && tmpValue["DataBase"].isObject()){
            if(tmpValue["DataBase"].isMember("dbpath") && tmpValue["DataBase"]["dbpath"].isString()){
                m_dbPath = tmpValue["DataBase"]["dbpath"].asString();
            }
            if(tmpValue["DataBase"].isMember("postionbl") && tmpValue["DataBase"]["postionbl"].isString()){
                m_position = tmpValue["DataBase"]["postionbl"].asString();
            }
        }
       qDebug() << "init: " << tmpValue.toStyledString().c_str();
    }
    m_handler = std::thread(&CDataManager::startHandlerProc, this);
    if(m_handler.joinable()){
        m_handler.detach();
    }
}
CDataManager::~CDataManager() {

}

bool CDataManager::initDB() {
    // 打开或创建 SQLite 数据库
    m_db = QSqlDatabase::addDatabase("QSQLITE");
    m_db.setDatabaseName(m_dbPath.c_str());
    if (!m_db.open()) {
        qDebug() << "Database connection failed:" << m_db.lastError().text();
        return false;
    }
    // 确保驱动程序已加载
    if (!QSqlDatabase::isDriverAvailable("QSQLITE")) {
        qDebug() << "Driver not loaded";
        return false;
    }
    // 检查并创建数据表
    return createPosTable("PositionData");

}

bool CDataManager::createPosTable(const QString& tableName) {
    if (!tableExists(tableName)) {
        QString createTableStmt = QString(
            "CREATE TABLE IF NOT EXISTS %1 ("
            "id INTEGER PRIMARY KEY AUTOINCREMENT,"
            "robotSn VARCHAR(255),"
            "dateTime DATETIME,"
            "position VARCHAR(255),"
            "width INTEGER,"
            "height INTEGER)"
        ).arg(tableName);
        QSqlQuery query;
        if (!query.exec(createTableStmt)) {
            qDebug() << "Failed to create table:" << query.lastError();
            return false;
        }
        qDebug() << "Table created successfully.";
    }
    return true;
}

bool CDataManager::tableExists(const QString& tableName) {
    QString query = QString("SELECT name FROM sqlite_master WHERE type='table' AND name='%1'").arg(tableName);
    qDebug() << "CDataManager::tableExists: " << query;
    QSqlQuery checkQuery;
    checkQuery.prepare(query);
    checkQuery.bindValue(0, tableName);
    return checkQuery.exec(query) && checkQuery.next();
}

QSqlDatabase CDataManager::dbConnection() {
    return m_db;
}

int CDataManager::queryTotalNumber(const QString& sql) {
    // 定义查询 SQL 语句，使用参数化查询来避免 SQL 注入
    //创建 QSqlQuery 对象并使用参数化查询
    QSqlQuery query(m_db);
    //绑定巡检参数，这里假设表名是一个已知的常量
    if (!query.exec(sql)) {
        qDebug() << "Failed to execute query:" << query.lastError();
        return -1;
    }
    //从查询结果中获取总数
    if(query.next()){
        return query.value(0).toInt(); //返回COUNT(*)的结果
    }else{
        qDebug() << "No data found or query did not successed. ";
        return 0;
    }
}

void CDataManager::keepalive() {
    // 执行一个简单的查询来 ping 数据库
    QSqlQuery query(m_db);
    if (!query.exec("SELECT 1")) {
        qDebug() << "Database connection failed. Please reconnect.";
    } else {
        qDebug() << "Database connection is alive.";
    }
}
void CDataManager::startHandlerProc(){
    while(true){
        keepalive();
        QString  querySql = QString("SELECT COUNT(*) FROM %1").arg(m_position.c_str());
        int currentTotalNum = queryTotalNumber(querySql);
        qDebug() <<"query currentTotalNum: " << currentTotalNum;
        std::this_thread::sleep_for(std::chrono::seconds(10));
    }
}
